package com.atguigu.gmall.serviceutil.redisson;

import com.atguigu.gmall.common.constans.RedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;

import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2025/8/31 22:15
 */
@Slf4j
@AutoConfigureAfter(RedisAutoConfiguration.class)
@Configuration
public class AppRedissonAutoConfig {

    @Autowired(required = false)
    List<BloomInitTask> bloomInitTasks;

    @Bean
    public RedissonClient redissonClient(RedisProperties redisProperties) {
        Config config = new Config();
        config.useSingleServer().
                setAddress("redis://" + redisProperties.getHost() + ":" + redisProperties.getPort())
                .setPassword(redisProperties.getPassword());
        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }

    @Bean
    public RBloomFilter<Object> skuIdBloom(RedissonClient redissonClient) {
        RBloomFilter<Object> skuIdBloom = redissonClient.getBloomFilter(RedisConstant.BLOOM_SKU_ID);

        if (skuIdBloom.isExists()) {
            log.info("skuIdBloom已存在");
            return skuIdBloom;
        }

        skuIdBloom.tryInit(1000000, 0.0001);
        for (BloomInitTask bloomInitTask : bloomInitTasks) {
            if (bloomInitTask instanceof SkuBloomTask) {
                log.info("SkuBloomTask开始初始化数据");
                bloomInitTask.initData(skuIdBloom);
            }else {
                log.error("未知的BloomInitTask类型");
            }
        }
        return skuIdBloom;
    }
}
